package tools.maf;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class mafParser {

	private BufferedReader reader;
	private boolean hasmore= true;
	private String s=null;
	private mafAlignment currHit= null;
	private mafAlignment nextHit= null;
	
	
	public mafParser(String file) throws Exception{
		this(new BufferedReader(new FileReader(file)));
	}
	
	/**
	 * 
	 * @param reader
	 * @throws IOException
	 * @throws BioException
	 */
	public mafParser(BufferedReader reader) throws Exception{
		this.reader= reader;
		nextLine();
		readNext();
	}
	
	public mafAlignment next() throws Exception{
		currHit=new mafAlignment(nextHit);
		readNext();
		return currHit;
	}
	
	public boolean hasNext() {
		return hasmore;
	}
	
	private void nextLine()throws Exception{
		s=reader.readLine();
//		System.err.println("A");
		
		while(s!=null &&(s.length()==0 || s.trim().charAt(0)=='#')){
//			System.err.println("B");
			s=reader.readLine();
		}
	}
	
	private void readNext() throws Exception{
//		System.err.println("C");
		if(s==null){
			nextHit= new mafAlignment();
			hasmore=false;
		}else{
			if(s.charAt(0)=='a'){
				nextHit= new mafAlignment(s);
				nextLine();
				if(s.charAt(0)!='s'){
					System.err.println("Unexpected line: "+s);
					readNext();
				}
				nextHit.addTargetSline(s);
				nextLine();
				if(s.charAt(0)=='q'){
					nextHit.addTargetQline(s);
					nextLine();
				}
				if(s.charAt(0)!='s'){
					System.err.println("Unexpected line: "+s);
					readNext();
				}
				nextHit.addQuerySline(s);
				nextLine();
				if(s.charAt(0)=='q'){
					nextHit.addQueryQline(s);
					nextLine();
				}
				hasmore=true;
			}else{
				nextLine();
				readNext();
			}
		}
	}
	
	public void close()throws IOException{
		reader.close();
	}

}
